package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuLockVo;
import com.spzx.product.api.domain.SkuPriceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-12-27
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private RemoteCartService remoteCartService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RemoteProductService remoteProductService;
    @Autowired
    private RemoteUserAddressService remoteUserAddressService;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private RemoteSkuStockService remoteSkuStockService;
    @Autowired
    private RabbitService rabbitService;


    // TODO 商品进行结算
    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityUtils.getUserId();
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        if (R.FAIL == cartCheckedListResult.getCode()) {
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        List<CartInfo> cartInfoList = cartCheckedListResult.getData();
//        if (CollectionUtils.isEmpty(cartInfoList)) {
//            throw new ServiceException("购物车无选中商品");
//        }
        if (!CollectionUtils.isEmpty(cartInfoList)) {
            List<OrderItem> orderItemList = cartInfoList.stream().map(cartInfo -> {
                OrderItem orderItem = new OrderItem();
                BeanUtils.copyProperties(cartInfo, orderItem);
                orderItem.setSkuNum(cartInfo.getSkuNum());
                return orderItem;
            }).collect(Collectors.toList());
            BigDecimal totalAmount = orderItemList.stream().map(orderItem -> orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()))).reduce(BigDecimal.ZERO, BigDecimal::add);
            String tradeNo = generateTradeNo(userId);
            TradeVo tradeVo = new TradeVo();
            tradeVo.setTradeNo(tradeNo);
            tradeVo.setTotalAmount(totalAmount);
            tradeVo.setOrderItemList(orderItemList);
            tradeVo.setIsBuy(false);
            return tradeVo;
        } else {
            throw new ServiceException("购物车无选中商品");
        }

    }

    //TODO 购物车进行结算后提交订单
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //TODO 1.用户提交订单
        //获取用户的userId
        Long userId = SecurityContextHolder.getUserId();
        //1 防止订单重复提交和停留页面超时
        String userTradeKey = "user:tradeNo:" + userId;
        String scriptText = """
                 if redis.call('get', KEYS[1]) == ARGV[1] then
                     redis.call('setex', KEYS[1], ARGV[2] , 'processed')
                     return 1
                 else
                    if redis.call('exists', KEYS[1]) == 1 then
                       return -1
                    else
                       return 0
                    end
                end
                """;
        Long flag = (Long) redisTemplate.execute(
                new DefaultRedisScript(scriptText, Long.class),
                List.of(userTradeKey),
                orderForm.getTradeNo(),
                300
        );
//        switch (flag){
//            case -1 : throw new ServiceException("请勿重复提交订单");
//            case 0 : throw new ServiceException("操作超时，请退回重试");
//            case 1 : break;
//            default: throw new ServiceException("未知错误: flag=%d");
//        }
        if (flag == 0) {
            throw new ServiceException("操作超时，请退回重试");
        }
        if (flag == -1) {
            throw new ServiceException("请勿重复提交订单");
        }
        //TODO 2.获取最新价格并判断价格是否改变
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<Long> skuIdList = orderItemList
                .stream()
                .map(OrderItem::getSkuId)
                .collect(Collectors.toList());
        //批量获取最新价格
        R<List<SkuPriceVo>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = skuPriceListResult.getData();
        //判断价格是否发生变化
        Map<Long, BigDecimal> skuIdSalePriceMap = skuPriceVoList.stream().collect(Collectors.toMap(
                SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice
        ));
        StringBuilder priceCheckResult = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuIdSalePriceMap.get(orderItem.getSkuId())) != 0) {
                //价格发生了变化
                priceCheckResult.append(orderItem.getSkuName()).append("\n");
            }
        }
        if (!StringUtils.isEmpty(priceCheckResult.toString())) {
            if (!orderForm.getIsBuy()) {
                remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
            }
            throw new ServiceException(priceCheckResult + "以上商品价格发生变化，请确认");
        }
        //TODO 3.校验库存并锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuName(orderItem.getSkuName());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).collect(Collectors.toList());
        R<String> checkAndLockResult = remoteSkuStockService.checkAndLock(
                orderForm.getTradeNo(),
                skuLockVoList,
                SecurityConstants.INNER);
        if (R.FAIL == checkAndLockResult.getCode()) {
            throw new ServiceException(checkAndLockResult.getMsg());
        }
        //TODO 4.下单并判断订单是否超时
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //下单失败，解锁库存
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.ROUTING_UNLOCK,
                    orderForm.getTradeNo());
            //抛出异常
            throw new ServiceException("下单失败");
        }
        String orderTimeKey = "user:orderTime:" + orderId;
        redisTemplate.opsForValue().set(orderTimeKey, orderId, 15, TimeUnit.MINUTES);
        //TODO 5.删除购物车选中商品
        if (!orderForm.getIsBuy()) {
            remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);
        }
        return orderId;
    }

    //TODO 点击立即购买进行结算(跳过购物车)
    @Override
    public TradeVo buy(Long skuId) {
        //获取商品SKU信息
        R<ProductSkuVo> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuResult.getCode()) {
            throw new ServiceException(productSkuResult.getMsg());
        }
        ProductSkuVo productSkuVo = productSkuResult.getData();
        //获取实时价格
        R<SkuPriceVo> skuPriceResult = remoteProductService.getSkuPrice(skuId, SecurityConstants.INNER);
        if (R.FAIL == skuPriceResult.getCode()) {
            throw new ServiceException(skuPriceResult.getMsg());
        }
        SkuPriceVo skuPriceVo = skuPriceResult.getData();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSkuVo.getSkuName());
        orderItem.setThumbImg(productSkuVo.getThumbImg());
        orderItem.setSkuPrice(skuPriceVo.getSalePrice());
        orderItem.setSkuNum(1);
        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        orderItemList.add(orderItem);
        String tradeNo = generateTradeNo(SecurityUtils.getUserId());
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(productSkuVo.getSalePrice());
        tradeVo.setIsBuy(true);
        tradeVo.setTradeNo(tradeNo);
        return tradeVo;
    }

    //TODO 查看订单列表
    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getUserId, userId)
                .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus);
        List<OrderInfo> orderInfoList = baseMapper.selectList(orderInfoLambdaQueryWrapper);

        if (!CollectionUtils.isEmpty(orderInfoList)) {
            List<Long> skuIdList = orderInfoList.stream().map(OrderInfo::getId).collect(Collectors.toList());
            LambdaQueryWrapper<OrderItem> itemLambdaQueryWrapper = new LambdaQueryWrapper<OrderItem>()
                    .in(OrderItem::getOrderId, skuIdList);

            List<OrderItem> orderItemList = orderItemMapper.selectList(itemLambdaQueryWrapper);

            Map<Long, List<OrderItem>> orderIdToOrderItemListMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
//            for (OrderInfo orderInfo : orderInfoList) {
            orderInfoList = orderInfoList.stream().map(orderInfo -> {
                        orderInfo.setOrderItemList(orderIdToOrderItemListMap.get(orderInfo.getId()));
                        String orderTimeKey = "user:orderTime:" + orderInfo.getId();
                        Object orderId = redisTemplate.opsForValue().get(orderTimeKey);
                        if (orderId == null && orderInfo.getOrderStatus() == 0) {
//                            orderInfo.setOrderStatus(-1);
//                            baseMapper.updateById(orderInfo);
                            cancelOrder(orderInfo.getId());
                        }
                        return orderInfo;
                    }).sorted(((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())))
                    .collect(Collectors.toList());
        }
        return orderInfoList;
    }


    //TODO 点击查看订单详情
    @Override
    public OrderInfo selectOrderInfoById(Long orderId) {
        if (orderId != null) {
            OrderInfo orderInfo = baseMapper.selectById(orderId);
            if (orderInfo != null) {
                LambdaQueryWrapper<OrderItem> orderItemLambdaQueryWrapper = new LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, orderId);
                List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemLambdaQueryWrapper);
                orderInfo.setOrderItemList(orderItemList);
                return orderInfo;
            }
        }
        return null;
    }

    //TODO 用户取消订单
    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus().intValue() == 0) {//待付款
            orderInfo.setOrderStatus(-1);//已取消
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            baseMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);
            //发送MQ消息通知商品系统解锁库存：TODO
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.ROUTING_UNLOCK,
                    orderInfo.getOrderNo());
        }
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(orderInfoLambdaQueryWrapper);
        LambdaQueryWrapper<OrderItem> itemLambdaQueryWrapper = new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderInfo.getId());
        List<OrderItem> orderItemList = orderItemMapper.selectList(itemLambdaQueryWrapper);
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    //TODO 更改订单支付信息
    @Override
    public void processPaySuccess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getOrderNo, orderNo)
                        .select(OrderInfo::getId, OrderInfo::getOrderStatus)
        );
        //幂等判断
        if(orderInfo.getOrderStatus() == 0) {
            orderInfo.setOrderStatus(1);//已支付
            orderInfo.setPaymentTime(new Date());
            baseMapper.updateById(orderInfo);
        }
    }

    //TODO 4.下单
    private Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();
        //todo 保存订单记录：order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(orderForm.getTradeNo());//订单号
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //远程调用获取用户地址信息
        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(userId, SecurityConstants.INNER);
        if (R.FAIL == userAddressResult.getCode()) {
            throw new ServiceException(userAddressResult.getMsg());
        }
        //获取用户地址信息
        UserAddress userAddress = userAddressResult.getData();
        //保存用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        //实时获取总价格
        //计算orderItem中商品的总价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = orderItemList.stream()
                .map(orderItem ->
                        orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //设置商品总价格
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));//优惠券价格
        orderInfo.setOriginalTotalAmount(totalAmount);//原价
        //订单状态
        orderInfo.setOrderStatus(0);
        orderInfo.setCreateBy(userName);
        orderInfo.setUpdateBy(userName);

        baseMapper.insert(orderInfo);
        //todo 保存订单项记录：order_item
        orderItemList.forEach(orderItem -> {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateBy(userName);
            orderItem.setUpdateBy(userName);
            orderItemMapper.insert(orderItem);
        });
        //todo 保存订单日志记录：order_log
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setOperateUser(userName);
        orderLog.setNote("提交订单");
        orderLog.setCreateBy(userName);
        orderLog.setUpdateBy(userName);
        orderLogMapper.insert(orderLog);
        return orderInfo.getId();
    }

    /**
     * 渲染订单确认页面-生成用户流水号
     */
    private String generateTradeNo(Long userId) {

        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 3, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 验证页面提交流水号是否有效
     */
    private Boolean checkTradeNo(Long userId, String tradeNo) {
        String userTradeKey = "user:tradeNo:" + userId;
        return Objects.equals(redisTemplate.opsForValue().get(userTradeKey), tradeNo);
    }

    /*
      删除流水号
      @param userId
     */
    private void deleteTradeNo(String userId) {
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }
}
